package com.job2e.common;

import java.io.File;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class MailSender {
	private String host;
	private String domain;
	private String user;
	private String password;
	private boolean auth;
	private JavaMailSender sender = null;
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private VelocityEngine velocityEngine;
	
	public MailSender(String host, String domain, String user, String password, boolean auth, VelocityEngine ve) {
		this.host = host;
		this.domain = domain;
		this.user = user;
		this.password = password;
		this.auth = auth;
		this.velocityEngine = ve;
		
		initSender();
	}
	
	private void initSender() {
		JavaMailSenderImpl ms = new JavaMailSenderImpl();
		ms.setHost(host);
		ms.setUsername(user);
		ms.setPassword(password);
	    Properties pp = new Properties();
	    pp.setProperty("mail.smtp.auth", String.valueOf(auth));
	    ms.setJavaMailProperties(pp);
	    
	    sender = ms;
	}

	public boolean send(final String subject, final String[] mailTo, final String body, final String[] files) {
		try {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
		           //注意MimeMessagePreparator接口只有这一个回调函数
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
					//这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
					//如果您使用的都是英文，那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
					message.setTo(mailTo);//设置接收方的email地址
					message.setSubject(subject);//设置邮件主题
					message.setFrom(user + "@" + domain);//设置发送方地址
					message.setText(body, true);
					//将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
					//如果您不想解析文本内容，可以使用false或者不添加这项
					FileSystemResource file;
					if (files != null && files.length > 0) {
					    for(String s:files)//添加附件
						{
						   file = new FileSystemResource(new File(s));//读取附件
						   message.addAttachment(s, file);//向email中添加附件
						}
					}
				}
			};
	
			sender.send(preparator);//发送邮件
			return true;
		}
		catch (Exception e) {
			log.error("Send mail error." + subject + "," + mailTo[0], e);
			return false;
		}
	}
	
	public boolean send(final String subject, final String[] mailTo, final String[] files, final String vmFile, final Map<String,Object> model) {
		try {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {
		           //注意MimeMessagePreparator接口只有这一个回调函数
				public void prepare(MimeMessage mimeMessage) throws Exception {
					MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
		            //这是一个生成Mime邮件简单工具，如果不使用GBK这个，中文会出现乱码
		            //如果您使用的都是英文，那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
		            message.setTo(mailTo);//设置接收方的email地址
		            message.setSubject(subject);//设置邮件主题
		            message.setFrom(user + "@" + domain);//设置发送方地址
		            String text = VelocityEngineUtils.mergeTemplateIntoString(
		            		velocityEngine, vmFile,"UTF-8", model);
		             //从模板中加载要发送的内容，vmfile就是模板文件的名字
		             //注意模板中有中文要加GBK，model中存放的是要替换模板中字段的值
		            message.setText(text, true);
		            //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
		            //如果您不想解析文本内容，可以使用false或者不添加这项
		            FileSystemResource file;
		            if (files != null && files.length > 0) {
			            for(String s:files)//添加附件
			            {
			               file = new FileSystemResource(new File(s));//读取附件
			               message.addAttachment(s, file);//向email中添加附件
			            }
		            }
		          }
		      };
		 
		      sender.send(preparator);//发送邮件
		      return true;
		}
		catch (Exception e) {
			log.error("Send mail error." + subject + "," + mailTo[0] + "," + vmFile, e);
			return false;
		}
	}
}
